package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.Connection ;
import java.sql.DriverManager;
import java.sql.PreparedStatement ;
import java.sql.ResultSet;
@WebServlet(name = "/login")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session=request.getSession();
        if ("1".equals(request.getParameter("invalidate"))&&session.getAttribute("username")!=null);
        {
            session.invalidate();
            response.sendRedirect("login.jsp");
        }
        try{
            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/book";
            Connection connection = DriverManager.getConnection(url,"root","root");

            String sql = "select * from user where username=? and password=?";
            PreparedStatement ps = connection.prepareStatement(sql);


            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out=response.getWriter();

            if (rs.next()){
                //response.sendRedirect("home.jsp");
                //out.print("登陆成功");
                session.setAttribute("username",username);
                response.sendRedirect("home.jsp");
            }else{
                //response.sendRedirect("login.jsp");
                out.print("登陆失败,3秒之后跳转登录页面...");
                response.setHeader("refresh","3;url=login.jsp");
        }

    }catch (Exception e){
        e.printStackTrace();
        }
    }

}
